package com.tb.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tb.mapper.PrisonMapper;
import com.tb.model.Prison;
import com.tb.model.PrisonExample;
import com.tb.util.MyConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @description: 小黑屋
 * @author: wangguichun
 * @create: 2018-03-28 17:05
 **/
@Service
public class PrisonService {

    @Autowired
    private PrisonMapper prisonMapper;
    @Autowired
    private UserService userService;

    public PageInfo<Prison> getUserListByPage(int pageId) {
        //获取前，清空已到期的记录
        clearPrisonByTimeIsOver();
        //按页取记录
//        int limit = (pageId - 1) * 15;
//        int offset = 15;
//        List<Prison> list = prisonMapper.selectListByLimit(limit, offset);
        PageHelper.startPage(pageId,MyConstant.PAGE_SIZE_USER);
        List<Prison> prisons = prisonMapper.selectByExample(null);
        for (Prison prison : prisons) {
            prison.setUser(userService.getUserById(prison.getUserId()));
        }
        return new PageInfo<>(prisons);
    }

    public int getCount() {
        return prisonMapper.countByExample(null);
    }


    public void deleteUserByUserId(Integer userId) {

        PrisonExample example = new PrisonExample();
        PrisonExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(userId);

        prisonMapper.deleteByExample(example);
    }

    public void addUser(int userId, int hour) {
        long startTime = new Date().getTime();
        long continueTime = hour * 60 * 60 * 1000;
        Prison prison = new Prison();
        prison.setUserId(userId);
        prison.setStartTime(startTime);
        prison.setContinueTime(continueTime);
        prisonMapper.insertSelective(prison);
    }

    //将禁闭时间已到的人清楚记录
    private void clearPrisonByTimeIsOver(){
        List<Prison> prisons = prisonMapper.selectByExample(null);
        long now = new Date().getTime();
        for (Prison prison : prisons) {
            if (prison.getStartTime() + prison.getContinueTime() < now){
                prisonMapper.deleteByPrimaryKey(prison.getId());
            }
        }
    }
}
